package consul

import (
	cfg "epg/jmconf"

	"github.com/hashicorp/consul/api"
)

func diff(s1, s2 api.KVPairs) map[string]cfg.Opt {
	diffs := make(map[string]cfg.Opt)
	m := make(map[string]api.KVPair)
	m2 := make(map[string]struct{}) //all the s2 keys
	for _, _v2 := range s2 {
		m2[_v2.Key] = struct{}{}
	}

	for _, v1 := range s1 {
		m[v1.Key] = *v1

		//s1 have, s2 don't have.
		if _, ok := m2[v1.Key]; !ok {
			diffs[v1.Key] = cfg.Opt{
				Op: cfg.OPDelete,
				KV: cfg.KV{Key: v1.Key, Val: v1.Value, LastIdx: v1.ModifyIndex},
			}
		}
	}

	for _, v2 := range s2 {
		if oldv, ok := m[v2.Key]; ok {
			if m[oldv.Key].ModifyIndex < v2.ModifyIndex {
				//both have, but different
				diffs[v2.Key] = cfg.Opt{
					Op: cfg.OPModify,
					KV: cfg.KV{Key: v2.Key, Val: v2.Value, LastIdx: v2.ModifyIndex},
				}
			}
		} else {
			//s1 don't have, s2 have
			diffs[v2.Key] = cfg.Opt{
				Op: cfg.OPAdd,
				KV: cfg.KV{Key: v2.Key, Val: v2.Value, LastIdx: v2.ModifyIndex},
			}
		}
	}
	return diffs
}
